<?php
namespace mytp;

use Exception;
class Api extends Container{
  protected $pathinfo;
  protected $res;
  protected $request;
  protected $debug = true;
  protected $rootPath;

  public function __construct($res = null){
    // 存放传递过来的 json数据
    $this->res = $res;
    $this->request = $this->make(Request::class);
    $this->rootPath = __DIR__. "./../config/database.php";
    DB::init(require $this->rootPath);
  }

  public function run () {
    try {
      $disPath = $this->checkRoute();
      return  $this->disPath($disPath);
    } catch(HttpException $e) {
      return $e->getResponse();
    } catch(Exception $e) {
      $msg = $this->debug ? $e->getMessage() : '';
      return Response::create('接口发生错误!! ' . $msg, 403);
    }

  }

  // 处理 pathinfo
  public function checkRoute() {
    $this->pathinfo = $this->request->pathinfo();
    if(empty($this->pathinfo)) throw new Exception('请求的URL错误!');
    require __DIR__.'/../../route/index.php';
    if(isset($routes[$this->pathinfo])){
      $this->pathinfo = $routes[$this->pathinfo];
    }    
    $arr = explode( '/',$this->pathinfo);
    $module = isset($arr[0]) ? ((empty($arr[0])) ? 'login' : $arr[0]) : 'login';
    $operation = isset($arr[1]) ? $arr[1] : 'index';
    return [$module,$operation];
  }

  // 请求分发,处理具体模块的具体方法
  public function disPath(array $disPath) {
    list($module, $operation) = $disPath;
    $modules = "\\modules\\".$module."\\".ucfirst($module);
    // echo $modules. "          --  Api.php line 39\n";
    if(!class_exists($modules)){
      // exit("该类不存在");
      $msg = " 请求的类: ". $modules . " 不存在!";
      throw new Exception($msg);
    } elseif(!method_exists($modules, $operation))  {
      // exit("该方法不存在");
      $msg = " 请求类 " . $modules . " 中的方法: ". $operation . " 不存在!";
      throw new Exception($msg);
    }
    $instance = ($this->make($modules))->$operation($this->res);
    $data = $instance;
    // echo "oh,no -- ".$data."<br>";
    // if(empty($data))
    //   return Response::create($data, 400, ["thinkPHP" => "5.1", "Vue" => "2.9.6"]);
    if(isset($data[1])&&$data[1] == 200) {
      return Response::create($data[0], $data[1], array_merge($data[2], ["thinkPHP" => "5.1", "Vue" => "2.9.6"]));
    }
    return Response::create($data, 200, ["thinkPHP" => "5.1", "Vue" => "2.9.6"]);
    // return Response::create($data, 200, ["thinkPHP" => "5.1", "Vue" => "2.9.6"]);
  }
}
?>